<template>
  <div class="personal-container">
    <!-- User info section -->
    <div class="user-info">
      <div class="avatar-section">
        <div class="avatar" v-if="avatarPath">
          <img :src="avatarPath" alt="" />
          <!-- 相机图标按钮 -->
          <div class="camera-icon" @click="showUploadOptions">
            <img :src="cameraIcon" class="cameraIcon" alt="更换头像" />
          </div>
        </div>
        <div v-else class="default-img">
          {{ studentName }}
          <!-- 相机图标按钮 -->
          <div class="camera-icon" @click="showUploadOptions">
            <img :src="cameraIcon" class="cameraIcon" alt="更换头像" />
          </div>
        </div>
        <!-- 上传选项弹窗 -->
        <van-action-sheet
          v-model:show="showOptions"
          :actions="uploadActions"
          @select="onSelectAction"
          cancel-text="取消"
          close-on-click-action
        />
        <!-- 隐藏的文件输入 -->
        <input
          type="file"
          ref="fileInput"
          accept="image/*"
          :capture="captureValue"
          @change="handleFileChange"
          style="display: none"
        />
      </div>
      <div class="right-section">
        <div class="name">
          <span>{{ studentName }}</span>
          <img :src="gender === '男' ? nanIcon : nvIcon" class="gender" alt="" />
        </div>
        <div class="student-no">学号: {{ studentNo }}</div>
      </div>
    </div>

    <!-- Personal info form -->
    <van-form @submit="handleSubmit">
      <van-cell-group>
        <van-field
          v-model="form.birthdate"
          name="birthDate"
          label="出生日期"
          placeholder="请选择出生日期"
          readonly
        />
        <van-field
          v-model="form.mobileNo"
          name="phone"
          label="联系电话"
          placeholder="请输入联系电话"
          type="number"
          :rules="[{ required: true, message: '请填写联系电话' }]"
        />
        <van-field
          v-model="form.studentHeight"
          name="height"
          label="身高(cm)"
          placeholder="请输入身高"
          type="number"
          :rules="[{ required: true, message: '请填写身高' }]"
        />
        <van-field
          v-model="form.studentWeight"
          name="weight"
          label="体重(kg)"
          placeholder="请输入体重"
          type="number"
          :rules="[{ required: true, message: '请填写体重' }]"
        />
      </van-cell-group>

      <div style="margin: 16px">
        <van-button block type="primary" native-type="submit"> 保存修改 </van-button>
      </div>
    </van-form>

    <!-- Date picker -->
    <!--
    <van-popup v-model:show="showBirthDatePicker" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="onBirthDateConfirm"
        @cancel="showBirthDatePicker = false"
      />
    </van-popup>
    -->
  </div>
</template>

<script setup lang="ts">
import nanIcon from '@/assets/img/nan.png'
import nvIcon from '@/assets/img/nv.png'
import cameraIcon from '@/assets/img/camera.svg'
import { ref, nextTick, onMounted } from 'vue'
import useUserStore from '@/stores/user'
import { showToast } from 'vant'
import { getStudentSettingInfo, resetStudentSettingInfoRequest } from '@/api/student'
import { uploadFile } from '@/api/upload'

const userStore = useUserStore()
const userInfo = userStore.userInfo
const avatarPath = ref(userInfo ? userInfo.avatarPath : '')
const studentName = userInfo ? userInfo.studentName : ''
const studentNo = userInfo ? userInfo.studentNo : ''
const gender = userInfo ? userInfo.gender : ''
const showOptions = ref(false)
const isCameraCapture = ref(false)
const fileInput = ref(null)

const form = ref({
  birthdate: '',
  mobileNo: '',
  studentHeight: '',
  studentWeight: '',
})
//
// const showBirthDatePicker = ref(false)
// const currentDate = ref(['1990', '01', '01'])

// const onBirthDateConfirm = ({ selectedValues }: { selectedValues: string[] }) => {
//   form.value.birthdate = selectedValues.join('-')
//   showBirthDatePicker.value = false
// }
// 上传选项
const uploadActions = ref([
  { name: '拍照', value: 'camera' },
  { name: '从相册选择', value: 'gallery' },
])

const captureValue = computed(() => (isCameraCapture.value ? 'camera' : undefined))
// 显示上传选项
const showUploadOptions = () => {
  showOptions.value = true
}

// 选择上传方式
const onSelectAction = (action) => {
  isCameraCapture.value = action.value === 'camera'

  // 重置文件输入框
  resetFileInput()

  // 确保DOM更新完成后再触发点击
  nextTick(() => {
    fileInput.value.click()
  })
}

// 重置文件输入框状态
const resetFileInput = () => {
  if (!fileInput.value) return

  // 清除之前的选择
  fileInput.value.value = ''

  // 动态设置capture属性
  if (isCameraCapture.value) {
    fileInput.value.setAttribute('capture', 'camera')
  } else {
    fileInput.value.removeAttribute('capture')
  }
}
// 处理文件选择
const handleFileChange = async (e) => {
  const file = e.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }

  // 验证文件大小 (限制10MB)
  if (file.size > 10 * 1024 * 1024) {
    showToast('图片大小不能超过10MB')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (event) => {
    avatarPath.value = event.target.result
  }
  reader.readAsDataURL(file)

  const res = await uploadFile(file)
  if (res.code == 200) {
    avatarPath.value = res.data.url
    userInfo.avatarPath = avatarPath.value
  }
}

const handleSubmit = async () => {
  // Submit logic here
  const submitRes = await resetStudentSettingInfoRequest({
    avatarPath: avatarPath.value,
    mobileNo: form.value.mobileNo,
    studentHeight: form.value.studentHeight,
    studentWeight: form.value.studentWeight,
  })
  // console.log('submitRes', submitRes)
  if (submitRes.code == 200) {
    showSuccessToast('提交成功！')
    getSettingInfo()
  }
}
const getSettingInfo = async () => {
  const res = await getStudentSettingInfo()
  form.value = res.data
  form.value.birthdate = form.value.birthdate?.substring(0, 10) || ''
}
onActivated(() => {
  getSettingInfo()
})
</script>

<style scoped>
.personal-container {
  padding: 20px;
}

.user-info {
  display: flex;
  /* justify-content: space-between; */
  align-items: center;
  margin-bottom: 30px;
}
.avatar {
  width: 80px;
  height: 80px;
  position: relative;
}
.avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  position: relative;
}

.right-section {
  display: flex;
  flex-direction: column;
  margin-left: 20px;
}
.default-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #d9d9d9;
  margin-bottom: 15px;
  position: relative;
}
.name {
  font-size: 14px;
  font-weight: bold;
}

.student-no {
  font-size: 12.254px;
  color: #666;
}
.gender {
  width: 12px;
  margin-left: 3px;
}
.avatar-section {
  font-size: 23px;
}
.camera-icon {
  display: flex;
  width: 20px;
  height: 20px;
  justify-content: center;
  align-items: center;
  position: absolute;
  right: 0;
  bottom: 0;
  background: #1989fa;
  padding: 4px;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;
  font-size: 16px;
  cursor: pointer;
}
.cameraIcon {
  width: 16px;
}
</style>
